using System;
using System.IO;
using System.Reflection;

using NUnit.Framework;
using System.Collections.Generic;

namespace Rsdn.SmartApp.Configuration
{
	[TestFixture]
	public class ConfigServiceTest
	{
		private static readonly string _exeDir =
			Path.GetDirectoryName(
				new Uri(Assembly.GetExecutingAssembly().CodeBase).AbsolutePath);

		private ServiceManager _svcMgr;
		private ExtensionManager _extMgr;

		[SetUp]
		protected void SetUp()
		{
			_svcMgr = new ServiceManager();
			_extMgr = new ExtensionManager(_svcMgr);
		}
		
		[Test]
		public void NormalRun()
		{
			ConfigService.CreateService(_svcMgr, _extMgr,
				typeof (ConfigServiceTest).Assembly.GetTypes(),
				Path.Combine(_exeDir, "Configuration\\testconfig.xml"),
				new Dictionary<string, string>());
			IConfigService svc = _svcMgr.GetService<IConfigService>();

			ISection1 sec1 = svc.GetSection<ISection1>();
			Assert.IsNotNull(sec1);
			Assert.AreEqual("Sample text", sec1.Text);

			ISection2 sec2 = svc.GetSection<ISection2>();
			Assert.IsNotNull(sec2);
			Assert.AreEqual(21, sec2.Number);

			ISection3 sec3 = svc.GetSection<ISection3>();
			Assert.IsNotNull(sec3);
			Assert.AreEqual(2, sec3.Values.Length);
			Assert.AreEqual("Value 1", sec3.Values[0]);
			Assert.AreEqual("Value 2", sec3.Values[1]);
		}

		[Test]
		[ExpectedException(typeof(InvalidOperationException))]
		public void SchemaValidationFail()
		{
			ConfigService.CreateService(_svcMgr, _extMgr,
				typeof(ConfigServiceTest).Assembly.GetTypes(),
				Path.Combine(_exeDir, "Configuration\\testconfig-invalid.xml"),
				new Dictionary<string, string>());
			IConfigService svc = _svcMgr.GetService<IConfigService>();
			ISection1 sec1 = svc.GetSection<ISection1>();
		}

		[Test]
		public void VarsTest()
		{
			ConfigService.CreateService(_svcMgr, _extMgr,
				typeof(ConfigServiceTest).Assembly.GetTypes(),
				Path.Combine(_exeDir, "Configuration\\testvars.xml"),
				new Dictionary<string, string> { { "Var2", "Value2" } });
			IConfigService svc = _svcMgr.GetService<IConfigService>();
			ISection4 sec4 = svc.GetSection<ISection4>();
			Assert.AreEqual("PrefixValue1Postfix", sec4.Name);
			Assert.AreEqual("PrefixValue2Postfix", sec4.Value.Trim());
		}
	}
}
